package com.geekyang.rabbitmqapi.dlx;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * @author ccyang
 * @date 2018/10/14 14:03
 * 消费端ACK 与 重回机制：自定义消费者
 */
public class MyConsumer extends DefaultConsumer{

    private Channel channel;

    public MyConsumer(Channel channel) {
        super(channel);
        this.channel = channel;
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                               byte[] body) throws IOException {

        System.err.println("-------------consumer message-------------");
        System.err.println("body：" + new String(body));

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if ((Integer)properties.getHeaders().get("num") == 0){
            // 第三个参数表示 是否让消息重回Broker端队列的尾部
            channel.basicNack(envelope.getDeliveryTag(), false, true);
        }else{
            // 手动签收, 第二个参数表示是否批量签收
            channel.basicAck(envelope.getDeliveryTag(), false);
        }

    }
}
